import {
  Button,
  Checkbox,
  Dialog,
  Image,
  Search,
  Stepper,
  Toast,
  SwipeCell,
  Navbar,
} from "@taroify/core";
import { View } from "@tarojs/components";
import ClearIcon from "@/assets/images/clear.png";
import { useEffect, useState } from "react";
import { requestPOST } from "@/request";
import Taro, { useDidShow } from "@tarojs/taro";
import { useSelector } from "react-redux";
import { RootState } from "@/store";

export default function ShopCar() {
  const merchantInfo = useSelector(
    (state: RootState) => state.userInfo.merchantInfo
  );

  const [list, setList] = useState<any>([]);
  const [searchName, setSearchName] = useState("");
  const baseUrl = process.env.TARO_APP_API;
  const [select, setSelect] = useState<any>([]);
  const [price, setPrice] = useState(0);
  const [checked, setChecked] = useState(false);

  const getList = () => {
    requestPOST("customerCart/getUserCartList", {
      isPage: 0,
      searchName,
    }).then((res: any) => {
      setList([...res.vos]);
    });
  };

  const handleChange = (value: any) => {
    setSelect([...value]);
    let result = 0;
    list.forEach((item) => {
      if (value.indexOf(item.id) !== -1) {
        result += item.productCurrentPrice * item.buyNum;
      }
    });
    setPrice(result);
  };

  const handleAllChange = (value) => {
    setChecked(value);
    if (value) {
      setSelect([...list.map((item) => item.id)]);
      let result = 0;
      list.forEach((item) => {
        result += item.productCurrentPrice * item.buyNum;
      });
      setPrice(result);
    } else {
      setSelect([]);
      setPrice(0);
    }
  };

  const BuyShop = () => {
    if (!select.length) {
      return Toast.open({ type: "fail", message: "请选择商品" });
    }
    Taro.navigateTo({
      url: `/packages/orderConfirm/index1?id=${select.join(",")}`,
    });
  };

  const clearShopCar = () => {
    Dialog.confirm({
      title: "提示",
      message: "您确定要清空购物车吗？",
      backdrop: {
        style: { zIndex: 10000 },
      },
      style: {
        zIndex: 10001,
      },
      onConfirm() {
        requestPOST(`customerCart/delCartProduct`, { isDelAll: 1 }).then(() => {
          Toast.open({ type: "success", message: "删除成功" });
          getList();
        });
      },
    });
  };

  const removeShop = (id) => {
    Dialog.confirm({
      title: "提示",
      message: "您确定要删除吗？",
      backdrop: {
        style: { zIndex: 10000 },
      },
      style: {
        zIndex: 10001,
      },
      onConfirm() {
        requestPOST(`customerCart/delCartProduct`, { cartIds: id }).then(() => {
          Toast.open({ type: "success", message: "删除成功" });
          getList();
        });
      },
    });
  };

  useDidShow(() => {
    getList();
    setSelect([]);
    setPrice(0);
    setChecked(false);
    // let value = [...list];
    // let result = 0;
    // select.forEach((item, index) => {
    //   if (list.find((item1) => item1.id == item)) {
    //     value.splice(index, 1, "");
    //   }
    // });
    // setList([...value].filter((item) => item));
    // [...value]
    //   .filter((item) => item)
    //   .forEach((item) => {
    //     result += item.productCurrentPrice * item.buyNum;
    //   });
    // setPrice(result);
  });
  return (
    <View
      className="taroContainer"
      style={{ display: "flex", flexDirection: "column" }}
    >
      <Navbar
        fixed
        nativeSafeTop
        safeArea="top"
        className="navBar"
        style={{ background: "#e3f3fe" }}
        placeholder={true}
      >
        <Navbar.Title style={{ maxWidth: "100%" }}>
          <View
            style={{
              display: "flex",
              alignItems: "center",
              width: "100vw",
              justifyContent: "center",
              position: "relative",
              fontSize: "28rpx",
              fontWeight: "normal",
            }}
          >
            <View style={{ position: "absolute", left: 20 }}>
              {merchantInfo.merchantName}
            </View>
            <View>订单收益</View>
          </View>
        </Navbar.Title>
      </Navbar>
      <View
        style={{ display: "flex", alignItems: "center", background: "#fff" }}
      >
        <View style={{ flex: 1 }}>
          <Search
            placeholder="请输入搜索关键词"
            value={searchName}
            onChange={(e) => setSearchName(e.detail.value)}
          />
        </View>
        <View
          style={{
            display: "flex",
            alignItems: "center",
            fontSize: "22rpx",
            color: "#F90000",
            marginRight: "20rpx",
            border: "1px solid #e9584b",
            padding: "10rpx 27rpx",
            gap: "10rpx",
            borderRadius: "7rpx",
          }}
          onClick={clearShopCar}
        >
          <Image src={ClearIcon} width={22} mode="widthFix" />
          <View>清除所选商品</View>
        </View>
      </View>

      <View
        style={{
          flex: "1",
          padding: "26rpx",

          overflowY: "auto",
        }}
      >
        <Checkbox.Group value={select} onChange={handleChange}>
          <View
            style={{ display: "flex", flexDirection: "column", gap: "20rpx" }}
          >
            {list.map((item, index) => (
              <SwipeCell>
                <View
                  key={item.id}
                  style={{
                    borderRadius: "14rpx",
                    boxShadow: "0rpx 1rpx 9rpx 0rpx rgba(59,59,59,0.19)",
                    display: "flex",
                    backgroundColor: "#fff",
                    alignItems: "center",
                    padding: "24rpx",
                    gap: "24rpx",
                  }}
                >
                  <Checkbox name={item.id} size={16}></Checkbox>
                  <Image
                    src={baseUrl + item.productImage}
                    width={180}
                    height={180}
                  />
                  <View
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      gap: "10rpx",
                      flex: 1,
                    }}
                  >
                    <View
                      style={{
                        gap: "20rpx",
                      }}
                    >
                      <View
                        style={{
                          fontSize: "25rpx",
                          color: "#333",
                          display: "inline",
                        }}
                      >
                        {item.productName}
                      </View>
                    </View>
                    <View
                      style={{
                        display: "flex",
                        alignItems: "baseline",
                      }}
                    >
                      <View
                        style={{
                          fontWeight: "bold",
                          fontSize: "21rpx",
                          color: "#f90000",
                        }}
                      >
                        ￥
                      </View>
                      <View
                        style={{
                          fontWeight: "bold",
                          fontSize: "33rpx",
                          color: "#f90000",
                        }}
                      >
                        {item.productCurrentPrice}
                      </View>
                      <View
                        style={{
                          fontSize: "21rpx",
                          color: "#AAAAAA",
                          textDecorationLine: "line-through",
                          marginLeft: "15rpx",
                        }}
                      >
                        ￥{item.productOriginalPrice}
                      </View>
                    </View>
                    <View style={{ fontSize: "21rpx", color: "#999999" }}>
                      已售{item.salesVolume || 0}
                    </View>
                    <View
                      style={{
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        fontSize: "20rpx",
                        color: "#333",
                      }}
                    >
                      <View>
                        总计：￥{item.productCurrentPrice * item.buyNum}
                      </View>
                      <View>
                        <Stepper
                          value={item?.buyNum}
                          onChange={(value) => {
                            list.splice(index, 1, {
                              ...list[index],
                              buyNum: value,
                            });
                            setList([...list]);
                          }}
                          step={1}
                          size={20}
                        />
                      </View>
                    </View>
                  </View>
                </View>

                <SwipeCell.Actions side="right">
                  <Button
                    variant="contained"
                    shape="square"
                    color="danger"
                    style={{ height: "100%" }}
                    onClick={() => removeShop(item.id)}
                  >
                    删除
                  </Button>
                </SwipeCell.Actions>
              </SwipeCell>
            ))}
          </View>
        </Checkbox.Group>
      </View>

      <View
        style={{
          background: "#fff",
          padding: "24rpx",
          display: "flex",
          alignItems: "center",
          gap: "45rpx",
        }}
      >
        <Checkbox
          style={{ color: "#666666", fontSize: "24rpx" }}
          size={16}
          checked={checked}
          onChange={handleAllChange}
        >
          全选
        </Checkbox>
        <View
          style={{ display: "flex", alignItems: "center", marginLeft: "auto" }}
        >
          <View style={{ color: "#333", fontSize: "25rpx" }}>总计：</View>
          <View
            style={{
              color: "#F90000",
              fontSize: "20rpx",
              fontWeight: "bold",
              display: "flex",
              alignItems: "baseline",
            }}
          >
            ￥<View style={{ fontSize: "33rpx" }}>{price}</View>
          </View>
        </View>

        <Button
          color="primary"
          style={{ background: "#F90000", border: "none", width: "222rpx" }}
          onClick={BuyShop}
        >
          去结算
        </Button>
      </View>
    </View>
  );
}
